package com.breeze.media.common;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

public abstract class BaseThreadManager {
    private HandlerThread mHandlerThread = null;
    private Handler mThreadHandler = null;
    private Handler mUiHandler = null;

    protected abstract String getTag();

    private HandlerThread getHandlerThread() {
        if (mHandlerThread == null) {
            mHandlerThread = new HandlerThread(getTag());
            mHandlerThread.start();
        }
        return mHandlerThread;
    }

    protected Handler getThreadHandler() {
        return mThreadHandler = mThreadHandler == null ?
                new ThreadHandler(getHandlerThread().getLooper()) : mThreadHandler;
    }

    protected Handler getUiHandler() {
        return mUiHandler = mUiHandler == null ? new UiHandler(Looper.getMainLooper()) : mUiHandler;
    }

    /**
     * 非主线程处理
     */
    private class ThreadHandler extends Handler {
        public ThreadHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            onThreadMessage(msg);
        }
    }

    /**
     * 主线程处理
     */
    private class UiHandler extends Handler {
        public UiHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            onUiMessage(msg);
        }
    }

    /**
     * 非主线程消息处理
     *
     * @param msg
     */
    protected void onThreadMessage(Message msg) {

    }

    /**
     * 主线程消息处理
     *
     * @param msg
     */
    protected void onUiMessage(Message msg) {

    }

    /**
     * 销毁,释放
     */
    public void release() {
        getHandlerThread().quitSafely();
        mHandlerThread = null;
        mThreadHandler = null;
        mUiHandler = null;
    }
}
